package day14;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import day13.JDBCUtil;
import day13.Student;

public class StudentManager {

	public static void main(String[] args) {
		while (true) {
			Scanner scanner = new Scanner(System.in);
			System.out.println("-------------------------");
			System.out.println("输入1：展示所有的学生");
			System.out.println("输入2：添加学生");
			System.out.println("输入3：根据id删除学生");
			System.out.println("输入4：根据条件搜索学生信息");
			System.out.println("输入5：根据id修改学生信息");
			System.out.println("输入0：退出");
			System.out.println("-------------------------");
			int type = scanner.nextInt();
			if (type == 0) {
				System.out.println("退出程序");
				break;
			}

			switch (type) {
			case 1:
				printAllStudent();
				break;
			case 2:
				insertStudent();
				break;
			default:
				break;
			}

		}
	}

	private static void insertStudent() {
		Scanner scanner = new Scanner(System.in);
		while (true) {
			System.out.println("请输入学生名字：");
			String name = scanner.next();
			System.out.println("请输入学生年龄：");
			int age = scanner.nextInt();
			System.out.println("请输入学生性别：");
			String gender = scanner.next();
			
			Connection connection = null;
			PreparedStatement statement = null;
			try {
				connection = JDBCUtil.getConnection();
				String sql = "insert into student(name,age,gender) values(?,?,?)";
				statement = connection.prepareStatement(sql);
				statement.setString(1, name);
				statement.setInt(2, age);
				statement.setString(3, gender);
				int count = statement.executeUpdate();
				System.out.println("count: " + count);
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				JDBCUtil.close(connection, statement, null);
			}
			
			System.out.println("0：退出 1：继续");
			int quit = scanner.nextInt();
			if (quit == 0) {
				break;
			}
		}
	}

	private static void printAllStudent() {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "select id,name,age,gender from student";
			statement = connection.prepareStatement(sql);
			resultSet = statement.executeQuery();
			List<Student> list = new ArrayList<Student>();
			// Moves the cursor forward one row from its current position.
			// Returns:true if the new current row is valid; false if there are no more rows
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				String gender = resultSet.getString("gender");
				Student student = new Student(id, name, age, gender);
				list.add(student);
			}
			for (Student student : list) {
				System.out.println(student);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
